package com.nopay.cdxphone.ui.ativity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.EditText;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.cdxphone.CallGroupEnum;
import com.nopay.cdxphone.Constants;
import com.nopay.cdxphone.R;
import com.nopay.cdxphone.base.BaseActivity;
import com.nopay.cdxphone.bean.request.SaveCallDataRequest;
import com.nopay.cdxphone.bean.response.SaveCallDataResponse;
import com.nopay.cdxphone.databinding.ActivityManualDialingBinding;
import com.nopay.cdxphone.dialog.DialogLoading;
import com.nopay.cdxphone.dialog.DialogPleaseOpenCallSetting;
import com.nopay.cdxphone.dialog.DialogWaitCallTransferSetting;
import com.nopay.cdxphone.receiver.PhoneBroadcastReceiver;
import com.nopay.cdxphone.ui.adapter.DialKeyboardAdapter;
import com.nopay.cdxphone.utils.CallLogHelper;
import com.nopay.cdxphone.utils.CallTransferUtil;
import com.nopay.cdxphone.utils.MemberManager;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ManualDialingActivity extends BaseActivity<ActivityManualDialingBinding> {

    private String mInputNum = "";
//    private Vibrator mVibrator;

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(v -> mSwipeBackHelper.backward());

        Class<EditText> cls = EditText.class;
        Method method;
        try {
            method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(binding.etPhoneNumber, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        DialKeyboardAdapter adapter = new DialKeyboardAdapter(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this);
        binding.gvDialKeyboard.setAdapter(adapter);
        binding.gvDialKeyboard.setOnItemClickListener((parent, view, position, id) -> {
//            if(mVibrator != null) mVibrator.vibrate(100);
            int index = getSelectionIndex();
            addChar(index, adapter.getItem(position));
        });

        binding.ibtnSetting.setOnClickListener(v -> {
//            if(!MemberManager.hasMemberPermission()) {
//                // TODO 提示开通会员才能使用
//                new DialogPleaseOpenMember(ManualDialingActivity.this).setOnOpenMemberConfirmListener(() -> {
//                    // TODO 确认开通会员
//                    mSwipeBackHelper.forward(RechargeActivity.class);
//                }).show();
//                return;
//            }

            if (ContextCompat.checkSelfPermission(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 120);
                return;
            }

//            int simStatus = CallTransferUtil.getSIMStatus(ManualDialingActivity.this);
//            if(simStatus == -1) {
//                ToastUtils.showShort("请插入SIM卡");
//                return;
//            }
//            mSwipeBackHelper.forward(simStatus  == 2 ? CallSettingForDoubleSIMActivity.class : CallSettingForSingleSIMActivity.class);

//            mSwipeBackHelper.forward(CallSettingForSingleSIMActivity.class);

            mSwipeBackHelper.forward(CallSettingActivity.class);
        });
        binding.ibtnPerson.setOnClickListener(v -> mSwipeBackHelper.forward(PhoneBookActivity.class));

        // 清除
        binding.ivClear.setOnClickListener(v -> {
            binding.etPhoneNumber.setText("");
            mInputNum = "";
        });
        // 删除上一个
        binding.ivDelete.setOnClickListener(v -> delChar(getSelectionIndex()));
        // 拨号
        binding.ivCall.setOnClickListener(v -> {
            if(TextUtils.isEmpty(mInputNum)) {
                ToastUtils.showShort("请输入手机号");
                return;
            }
            if(!MemberManager.hasMemberPermission()) {
                if(!MemberManager.hasFreeTimes()) {
                    ToastUtils.showShort("今日免费次数已用完");

//                    new DialogPleaseOpenMember(ManualDialingActivity.this).setOnOpenMemberConfirmListener(() -> {
//                        // TODO 开通会员
//                        mSwipeBackHelper.forward(RechargeActivity.class);
//                    }).show();
                    return;
                }
            }

            if(!SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false)) {
                new DialogPleaseOpenCallSetting(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this).setOnOpenCallSettingConfirmListener(() -> {
                    // TODO 开启防封设置
                    mSwipeBackHelper.forward(CallSettingActivity.class);
                }).show();
                return;
            }

            MemberManager.addUseTimes();
            if(CallTransferUtil.open(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this, mInputNum)) {
                if(SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                    initDianXinCallFinishListener(mInputNum);
                } else {
                    initCallFinishListener(mInputNum);
                    new DialogWaitCallTransferSetting(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this)
                            .setOnWaitFinishListener(() -> CallTransferUtil.call(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this, ""))
                            .show(SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TIME_OUT, Constants.CALL_TRANSFER_DEFAULT_TIME_OUT));
                }
            } else {
                initCallFinishListener(mInputNum);
                CallTransferUtil.call(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this, mInputNum);
            }
            binding.etPhoneNumber.setText("");
            mInputNum = "";
        });

        binding.etPhoneNumber.setOnPasteListener(() -> {
            mInputNum = binding.etPhoneNumber.getText().toString().trim();
        });

        // 耗时操作在现场中执行
        new Thread(() -> getCallLog(0)).start();
    }

    /**
     * addChar
     * @param index
     * @param s 添加的字符
     */
    private void addChar(int index, String s) {
        if (index == binding.etPhoneNumber.getText().toString().trim().length()) {
            mInputNum += s;
            binding.etPhoneNumber.setText(mInputNum);
            binding.etPhoneNumber.setSelection(binding.etPhoneNumber.getText().toString().trim().length());
        } else {
            StringBuilder sb = new StringBuilder(mInputNum);
            sb.insert(index, s);
            mInputNum = sb.toString();
            binding.etPhoneNumber.setText(mInputNum);
            binding.etPhoneNumber.setSelection(index);
        }
    }

    private int getSelectionIndex() {
        int index = 0;
        if (!TextUtils.isEmpty(binding.etPhoneNumber.getText().toString().trim())) {
            index = binding.etPhoneNumber.getSelectionStart();
        }
        return index;
    }

    private void delChar(int index) {
        if (index == binding.etPhoneNumber.getText().toString().trim().length()) {
            try {
                mInputNum = mInputNum.substring(0, mInputNum.length() - 1);
            } catch (StringIndexOutOfBoundsException e) {
                e.printStackTrace();
            }
            binding.etPhoneNumber.setText(mInputNum);
            binding.etPhoneNumber.setSelection(binding.etPhoneNumber.getText().toString().trim().length());
        } else {
            if (index > 0){
                String delStr = "";
                //注意for循环里的++
                for (int i = 0; i < binding.etPhoneNumber.getText().toString().trim().length(); i++) {
                    if (index - 1 != i ) {
                        try {
                            delStr += binding.etPhoneNumber.getText().toString().trim().charAt(i);
                        } catch (StringIndexOutOfBoundsException e) {
                            e.printStackTrace();
                        } catch (IndexOutOfBoundsException e){
                            e.printStackTrace();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
                mInputNum = delStr;
                binding.etPhoneNumber.setText(mInputNum);
                try{
                    binding.etPhoneNumber.setSelection(index - 1);
                }catch (IndexOutOfBoundsException e){
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public void initDianXinCallFinishListener(String phoneNumber) {
        PhoneBroadcastReceiver.setOnCallFinishListener((status, callLogItem) -> {
            if(status == 1) {
                new Handler().postDelayed(() -> {
                    initCallFinishListener(phoneNumber);
                    CallTransferUtil.call(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this, "");
                }, 100);
            }
        });
    }

    public void initCallFinishListener(String phoneNumber) {
        PhoneBroadcastReceiver.setOnCallFinishListener((status, callLogItem) -> {
            if(status == 0) {
                if(mLoading == null) mLoading = new DialogLoading(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this);
                if(!isFinishing()) mLoading.show("正在保存通话记录...");
            }

            if(status == 1) {
                if(callLogItem != null) {
                    // 保存通话记录
                    saveCallData(phoneNumber, callLogItem.getDate(), callLogItem.getDuration(), 0);
                } else {
                    // 保存通话记录
                    @SuppressLint("SimpleDateFormat") String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    saveCallData(phoneNumber, dateStr, 0, 0);
                }

                if(!SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                    boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
                    if(isOpen && !isFinishing()) CallTransferUtil.close(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this);
                }
            }

//            new Thread(() -> {
//                CallLogHelper.CallLogItem callLogItem = getCallLog(5);
//                if(callLogItem != null) {
//                    // 保存通话记录
//                    saveCallData(phoneNumber, callLogItem.getDate(), callLogItem.getDuration(), 0);
//                } else {
//                    // 保存通话记录
//                    @SuppressLint("SimpleDateFormat") String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//                    saveCallData(phoneNumber, dateStr, 0, 0);
//                }
//
//                boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
//                if(isOpen) CallTransferUtil.close(ManualDialingActivity.this);
//            }).start();
        });
    }

    private CallLogHelper.CallLogItem getCallLog(int times) {
        CallLogHelper.CallLogItem callLogItem = CallLogHelper.fetchNewCallLog(com.nopay.cdxphone.ui.ativity.ManualDialingActivity.this);
        if(callLogItem == null) {
            if(times > 0) {
                times--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCallLog(times);
            }
        }
        return callLogItem;
    }

    private DialogLoading mLoading;

    public void saveCallData(String phoneNumber, String dateStr, int duration, int saveTimes) {
        SaveCallDataRequest bean = new SaveCallDataRequest();
        bean.setCallDate(dateStr);
        bean.setCalledNumber(phoneNumber);
//                    String callingNumber = CallTransferUtil.getPhoneNumberBySubId(ManualDialingActivity.this, subId);
        String callingNumber = CallTransferUtil.getPhoneNumberByCallSetting();
        bean.setCallingNumber("".equals(callingNumber) ? "未知" : callingNumber);
        bean.setCompany("");
        bean.setDuration(duration);
        bean.setName("");
        bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
        bean.setStatus(duration > 0 ? 1 : 2);
        bean.setTaskId(CallGroupEnum.IMPORT_MANUAL.getGroupId());

        RequestBody body = getRequestBody(bean);
        api.doSaveCallData(body).enqueue(new Callback<SaveCallDataResponse>() {
            @Override
            public void onResponse(Call<SaveCallDataResponse> call, Response<SaveCallDataResponse> response) {
                if(mLoading != null) {
                    mLoading.dismiss();
                    mLoading = null;
                }

                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        ToastUtils.showShort("通话记录已保存");
                        return;
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
                if(saveTimes < 3) new Handler().postDelayed(() -> saveCallData(phoneNumber, dateStr, duration, saveTimes + 1), 3000);
            }

            @Override
            public void onFailure(Call<SaveCallDataResponse> call, Throwable t) {
                if(mLoading != null) {
                    mLoading.dismiss();
                    mLoading = null;
                }

                ToastUtils.showShort(getResources().getString(R.string.call_api_error));
                if(saveTimes < 3) new Handler().postDelayed(() -> saveCallData(phoneNumber, dateStr, duration, saveTimes + 1), 3000);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLoading != null) {
            mLoading.dismiss();
            mLoading = null;
        }
    }
}
